<template>
  <div>
    <el-container style="background: #f5f7f9;">
      <el-header style="background: #fff;padding: 12px 12px;height:auto;">
        <div>
          <el-form :model="queryData" :inline="true" size="small">
            <el-form-item label="状态">
              <el-radio-group v-model="queryData.status" size="small" @change="queryOrder()">
                <el-radio-button label="all">所有订单</el-radio-button>
                <el-radio-button label="cancelled">已删除</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="产品">
              <el-select v-model="queryData.channelId" clearable filterable>
                <el-option v-for="(item, i) in channelOptions" :key="i" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户">
              <el-select v-model="queryData.orgOwner" clearable filterable>
                <el-option v-for="(d, i) in customerOptions" :key="i" :label="d.orgOwnerName" :value="d.orgOwner" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="queryData.orderId" :rows="1" style="width: 280px;" type="textarea" placeholder="多个单号用回车分割" />
            </el-form-item>
            <el-form-item label="客户订单号">
              <el-input v-model="queryData.customerRef" :rows="1" style="width: 280px;" type="textarea" placeholder="多个单号用回车分割" />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="queryData.createAtRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchData()">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main style="margin-top: 15px; background: #fff;padding: 12px 16px 0 16px;height: 100%;">
        <div style="height: 100%;display: flex;">
          <template v-if="queryData.status !== 'cancelled'">
            <!-- <el-button size="small" class="btn-cyan" @click="exportOrders">导出订单</el-button> -->
            <el-button size="small" @click="deleteOrders">删除</el-button>
            <el-button size="small" @click="download">导出</el-button>
          </template>
        </div>
        <el-table ref="multipleTable" :data="tableData" stripe tooltip-effect="dark" :max-height="tableHeight" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="orderNumber" fixed label="订单号" />
          <el-table-column prop="customerRef" label="客户订单号" />
          <el-table-column prop="orgOwnerName" label="客户" />
          <el-table-column prop="channelName" label="产品" />
          <el-table-column prop="totalCarton" label="托数" />
          <el-table-column prop="totalWeight" label="总重量" />
          <el-table-column prop="createAt" label="创建时间" />
          <el-table-column prop="status" label="订单状态" />
          <el-table-column prop="totalChargePrepaid" label="预付费用" />
          <el-table-column prop="totalCharge" label="实付费用" />
          <el-table-column prop="totalChargeDiff" label="费用差" />
          <el-table-column prop="totalCostPrepaid" label="预估成本" />
          <el-table-column prop="totalCost" label="实际成本" />
          <el-table-column prop="totalCostDiff" label="成本差异" />
          <el-table-column v-if="queryData.status !== 'cancelled'" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button size="small" shape="circle" type="text" @click="showDetail(scope.row)">明细</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer style="padding:0;background: #fff;">
        <div style="text-align: right; padding-top: 10px;">
          <!-- 分页 -->
          <el-pagination background :current-page="queryData.currentPage" :page-sizes="[50, 100, 200, 300, 400]" :page-size="queryData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" style="float: right;" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-footer>
    </el-container>
    <Detail ref="detail" />
  </div>
</template>

<script>
import { mapState } from 'vuex'
import request from '@/utils/request'
import config from '@/settings'
import { copyProperty } from '@/utils/tools'
const BASE_URL = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
import Detail from './detail'
export default {
  components: { Detail },
  data() {
  return {
    pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      detailOrderId: '',
      importOrderUrl: BASE_URL + '/order/import-order2',
      importOrderFileList: [],
      importFbaOrderUrl: BASE_URL + '/order/import-fba-order2',
      importOrderDialogShow: false,
      importOrderDialogShow2: false,
      batch_upload_mask: false,
      batch_download_label: false,
      formLabelWidth: '120px',
      downloadLabelCtx: {
        date: '',
        orderIds: ''
      },
      detailDialogVisible: false,
      conditions: {
        export: 0,
        status: '',
        product: '',
        number: '',
        startDate: '',
        endDate: '',
        orgId: '',
        currentPage: 1,
        pageSize: 100,
        trackingNumbers: []
      },
      queryData: {
        pageSize: 50,
        currentPage: 0,
        orgOwner: '',
        orderId: '',
        customerRef: '',
        channelId: '',
        status: 'all',
        createAtRange: []
      },
      detailDefault: {
        orderNumber: '',
        channelName: '',
        customerRef: '',
        consigneeAddress: {
          contacter: '',
          phone: '',
          countryCode: '',
          state: '',
          city: '',
          address: '',
          address2: '',
          company: '',
          zipCode: '',
          fbaCode: '',
          deliverySignature: 'false'
        },
        cartons: [],
        createAt: '',
        orgOwnerName: '',
        totalCarton: 0,
        totalVolume: '',
        totalWeight: '',
        txs: [],
        packingListTableBody: [],
        trackingNumbers: []
      },
      detail: {
        orderNumber: '',
        channelName: '',
        customerRef: '',
        consigneeAddress: {
          contacter: '',
          phone: '',
          countryCode: '',
          state: '',
          city: '',
          address: '',
          address2: '',
          company: '',
          zipCode: '',
          fbaCode: '',
          deliverySignature: 'false'
        },
        cartons: [],
        createAt: '',
        orgOwnerName: '',
        totalCarton: 0,
        totalVolume: '',
        totalWeight: '',
        txs: [],
        packingListTableBody: [],
        trackingNumbers: []
      },
      detailExpandItemsDefault: ['1', '2'],
      detailExpandItems: ['1', '2'],
      numberTextArea: '',
      trackingNumbers: '',
      orgs: [],
      tableData: [],
      multipleSelection: [],
      customerList: [],
      currentPage: 1, // 分页
      dialogFormVisible: false,
      dialogUpLoadVisible: false,
      dialogCheckVisible: false,
      checkForm: {
        radio: '1',
        text: ''
      },
      total: 0,
      createOrderform: {
        product: '',
        customer: ''
      },
      createOrderformRules: {
        product: [{ required: true, message: '请选择产品', trigger: 'change' }],
        customer: [{ required: true, message: '请选择客户', trigger: 'change' }]
      },
      channelProduct: [],
      channelMap: {},
      statusMap: {},
      isAdmin: false,
      orderCostData: []
    }
  },
  computed: {
    tableHeight() {
      return document.documentElement.clientHeight - 250
    },
    ...mapState(//
      {
        paymentTerm: state => state.base.paymentTerm,
        customerOptions: state => state.base.customerOptions,
        channelOptions: state => state.base.channelOptions,
        profile: state => state.user,
        orderStatusOptions: state => state.base.orderStatusOptions
      }
    )
  },
  created() {
    this.queryOrder()
  },
  methods: {
    download() {
      const orderNumber = []
      this.multipleSelection.forEach(e => {
        orderNumber.push(e.orderNumber)
      })
      this.queryData.orderId = orderNumber.join('\n')
      if (this.queryData.orgOwner || this.queryData.orderId ||
      this.queryData.customerRef || this.queryData.channelId ||
      (this.queryData.createAtRange && this.queryData.createAtRange.length === 2)) {
        request({
          url: 'order/download',
          data: this.queryData,
          method: 'post'
        }).then(res => {
          this.queryData.orderId = ''
          if (res.success) {
            const link = document.createElement('a')
            const array = this.base64ToUint8Array(res.data)
            const blob = new Blob([array])
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', `订单明细.xlsx`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        })
      } else {
        this.$message({
          message: '请先选择条件',
          type: 'error'
        })
      }
    },
    downloadTrackingNumber() {
      const orderNumber = []
      this.multipleSelection.forEach(e => {
        orderNumber.push(e.orderNumber)
      })
      this.queryData.orderId = orderNumber.join('\n')
      if (this.queryData.orgOwner || this.queryData.orderId ||
      this.queryData.customerRef || this.queryData.channelId ||
      (this.queryData.createAtRange && this.queryData.createAtRange.length === 2)) {
        request({
          url: 'order/download/tracking-mumber',
          data: this.queryData,
          method: 'post'
        }).then(res => {
          this.queryData.orderId = ''
          if (res.success) {
            const link = document.createElement('a')
            const array = this.base64ToUint8Array(res.data)
            const blob = new Blob([array])
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', `快递单号.xlsx`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        })
      } else {
        this.$message({
          message: '请先选择条件',
          type: 'error'
        })
      }
    },
    base64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4)
      const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)
      for (let i = 0; i < rawData.length; ++i) {
          outputArray[i] = rawData.charCodeAt(i)
      }
      return outputArray
    },
    cartonTableSpanMethod(row) {
      if (!row.row.skuNameEn) {
        return [1, 1]
      }
      if (row.row.rowSpan > 0 && row.columnIndex <= 4) {
        return [row.row.rowSpan, 1]
      } else if (row.columnIndex > 4) {
        return [1, 1]
      } else if (row.columnIndex <= 4) {
        return [0, 1]
      }
    },
    importOrderCallBack(res) {
      if (res.success) {
        this.$message.success('成功')
        this.importOrderDialogShow = false
        this.importOrderDialogShow2 = false
        this.importOrderFileList = []
        this.queryOrder()
      } else {
        this.importOrderFileList = []
        this.$message({
          message: res.message,
          type: 'error',
          duration: 0,
          showClose: true
        })
      }
    },
    importFbaOrderCallBack(res) {

    },
    showBatchDownloadLabel() {
      this.batch_download_label = true
    },
    hideBatchDownloadLabel() {
      this.batch_download_label = false
    },
    doBatchDownloadLabel() {
      var _this = this
      if (_this.lm_system) {
        if (!_this.downloadLabelCtx.orderIds) {
          this.$notify.info({
            title: '提示',
            message: '请输入订单号'
          })
          return
        }
      } else {
        if (!_this.downloadLabelCtx.date) {
           this.$notify.info({
            title: '提示',
            message: '请选择日期'
        })
        return
        }
      }
    },
    exportCharge() {
    },
    searchData() {
      this.queryData.currentPage = 1
      this.queryOrder()
    },
    // 搜索
    queryOrder() {
      request({
        url: 'truck2/query',
        data: this.queryData,
        method: 'post'
      }).then(res => {
        if (res.success) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    getLabels() {
      const _this = this
      const orderIds = []
      if (_this.multipleSelection.length === 0) {
        _this.$message.error('请选择订单')
        return
      }
      _this.multipleSelection.forEach(a => {
        orderIds.push(a.id)
      })
      window.open()
    },
    deleteOrders() {
      const orderIds = []
      if (this.multipleSelection.length === 0) {
       this.$message.error('请选择订单')
        return
      }
      this.multipleSelection.forEach(a => {
        orderIds.push(a.orderId)
      })
      this.$confirm('是否取消订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: 'truck2/dels',
          data: { orderIds: orderIds },
          method: 'post'
        }).then(res => {
          if (res.success) {
            this.queryOrder()
          }
        })
      })
    },
    exportOrders() {
      const _this = this
      _this.conditions.number = []
      _this.numberTextArea.split(/\n+/gim).forEach((d, i) => {
        if (d && d != '') {
          _this.conditions.number.push(d)
        }
      })

      let notStatus = []
      const s = _this.conditions.status
      if (s == '') {
        notStatus = ['cancelled', 'exception']
      } else if (s == 'cancelled') {
        notStatus = ['exception']
      }

      var submitForm = {
        status: _this.conditions.status,
        orgId: _this.conditions.orgId,
        productId: _this.conditions.product,
        orderId: _this.conditions.number,
        startDate: _this.conditions.startDate,
        endDate: _this.conditions.endDate,
        currentPage: _this.conditions.currentPage,
        pageSize: _this.conditions.pageSize,
        notStatus: notStatus,
        export: 1,
        orderIds: []
      }
      _this.multipleSelection.forEach(a => {
        submitForm.orderIds.push(a.id)
      })
    },
    // 查看
    showDetail(row) {
      this.$refs.detail.show(row)
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('是否取消的订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

      })
    },
    restore(index, row) {
      this.$confirm('是否恢复订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
        })
        .catch(() => {})
    },
    downloadLabel(row) {
      request({
        url: '/d/lm-label?orderId=' + row.orderId,
        method: 'get'
      }).then(res => {
        if (res.success) {
            window.open(res.data)
        }
      })
    },
    // 多选按钮
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 分页
    handleSizeChange(val) {
      this.queryData.currentPage = 1
      this.queryData.pageSize = val
      this.queryOrder()
    },
    handleCurrentChange(val) {
      this.queryData.currentPage = val
      this.queryOrder()
    }
  }
}
</script>
